package cn.gotom.core.web;


import java.io.Serializable;

import org.apache.log4j.Logger;

import cn.gotom.util.Base64;
import cn.gotom.util.Converter;


public class UserCookie implements Serializable
{
	public static void main(String[] args)
	{
		UserCookie uc = new UserCookie("username", "password");
		System.out.println(uc.toString());
		UserCookie uc2 = new UserCookie(uc.toString());
		System.out.println(uc2.getUsername());
		System.out.println(uc2.getPassword());
	}

	private static final long serialVersionUID = 1L;
	protected final Logger log = Logger.getLogger(getClass());

	private final static String COOKIE_KEY = "cookie==";// "CD0125A421D8E1B6C6CFB099F46C6502==";

	private String username;
	private String password;

	public UserCookie(String username, String password)
	{
		this.username = username;
		this.password = password;
	}

	public UserCookie(String cookie)
	{
		try
		{
			cookie = cookie.replace(COOKIE_KEY, "");
			if (cookie.length() > 4)
			{
				cookie = new String(Base64.decode(cookie, Base64.DEFAULT));
				int len = Integer.parseInt(cookie.substring(0, 8), 16);
				this.username = cookie.substring(8, len + 8);
				this.password = cookie.substring(len + 8, cookie.length());
			}
		}
		catch (Exception ex)
		{
			this.username = null;
			this.password = null;
		}
	}

	public String getUsername()
	{
		return username;
	}

	public void setUsername(String username)
	{
		this.username = username;
	}

	public String getPassword()
	{
		return password;
	}

	public void setPassword(String password)
	{
		this.password = password;
	}

	public String toString()
	{

		byte[] bf = Converter.GetBytes(username.length());
		byte[] buffer = new byte[bf.length];
		for (int i = 0; i < buffer.length; i++)
		{
			buffer[i] = bf[buffer.length - 1 - i];
		}
		StringBuffer sb = new StringBuffer();
		sb.append(COOKIE_KEY);
		sb.append(Converter.toHexString(buffer).replace(" ", ""));
		sb.append(username);
		sb.append(password);
		log.debug(sb);
		return sb.toString();
	}
}
